let CONFIG = require('../config/config');
let db = require('../config/db');

function getlist(req, res) {

    //定义页码
    let page = req.query.page || 1;

    //搜索关键词
    let search = req.query.search || '';

    //商品总数
    let total = 0;

    //偏移量 -- 分页查询的 开始 行序号
    let offset = 0;

    //总页数
    let pageCount = 0;

    //页尺寸
    let pageSize = 6;

    //查询数据总行数
    let sqlStr = `select count(*) as num from goods where name like '%${search}%'`;
    db.query(sqlStr, (err, rst) => {
        //总行数
        total = rst[0].num;
        //偏移量
        offset = (page - 1) * pageSize;
        //计算总页数
        pageCount = Math.ceil(total / pageSize);

        //查询当前页数据
        sqlStr = `select * from goods where name like '%${search}%' limit ${offset},${pageSize}`;
        db.query(sqlStr, (err, rst) => {
            let status = {
                code: CONFIG.SUCCESS.code,
                msg: CONFIG.SUCCESS.msg,
                data: rst,
                page: {
                    pageNo: parseInt(page),
                    pageCount: pageCount,
                    total: total,
                    pageSize: pageSize
                }
            };
            return res.send(status);
        });

    });


}

//获取 商品详情
function getinfo(req, res) {

    //接收商品ID
    let id = req.query.id;

    //定义SQL
    let sqlStr = `select * from goods where id=${id}`;

    //执行SQL
    db.query(sqlStr, (err, rst) => {

        //判断是否执行错误
        if (err) {
            return res.send(CONFIG.FAIL);
        }

        //判断结果集中是否有数据
        if (rst.length > 0) {
            // 组装 响应数据 对象
            let status = {
                ...CONFIG.SUCCESS,
                data: rst[0] // 商品行
            };
            // 发送给浏览器
            return res.send(status);
        } else {
            return res.send(CONFIG.RESULT_NULL);
        }
    });
}

module.exports = {
    getlist,
    getinfo
}